class Assignment < ActiveRecord::Base
  belongs_to :job
  belongs_to :user
  
  validates_presence_of :job_id
  validates_presence_of :user_id
  
  # This validation currently doesn't work, so we have to 
  # do a manual one, but this will soon be fixed in a future version of Rails
  validates_associated :job, :user

  def self.exists?(job_id_to_test, user_id_to_test)
    self.find_by_job_id_and_user_id(job_id_to_test, user_id_to_test) ? true : false
  end
  
  protected
    def validate
      errors.add(:job_id, "is invalid") unless Job.find_by_id(job_id)
      errors.add(:user_id, "is invalid") unless User.find_by_id(user_id)
    end
    
    def validate_on_create
      errors.add_to_base("Already exists") if Assignment.exists?(job_id, user_id)
    end
end
